package org.pro.core.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.pro.core.ResponseMessage;
import org.pro.core.constant.SecurityConstants;
import org.pro.core.properties.SecurityProperties;
import org.pro.core.social.SocialUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

@RestController
public class BrowserSecurityController {

	//获取引发跳转的请求
	private RequestCache requestCache = new HttpSessionRequestCache();
	//重定向请求工具
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	
	@Autowired
	private SecurityProperties securityProperties;
	@Autowired
	private ProviderSignInUtils providerSignInUtils;
	
	@RequestMapping(value = SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED) //未认证状态码
	public ResponseMessage requestAuthorized(HttpServletRequest request,HttpServletResponse response) throws IOException {
		SavedRequest savedRequest = requestCache.getRequest(request, response);
		if(savedRequest!=null) {
			//String targetUrl=savedRequest.getRedirectUrl();
			if(!securityProperties.getLoginType().equals("json")) {
				redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginUrl());
			}
		}
		ResponseMessage res = new ResponseMessage();
		res.setMessage("未登录，跳转到登录页面");
		return res;
	}
	
	/**
	 * 在第三方登录时，临时保存第三方信息
	 * @param request
	 * @return
	 */
	@GetMapping("/social/user")
	public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
		SocialUserInfo userInfo=new SocialUserInfo();
		Connection<?> connection=providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
		userInfo.setProviderId(connection.getKey().getProviderId());
		userInfo.setProviderUserId(connection.getKey().getProviderUserId());
		userInfo.setNickname(connection.getDisplayName());
		userInfo.setHeadImg(connection.getImageUrl());
		return userInfo;
	}
}
